import java.io.*;
import java.util.*;

public class Main{
	public static void main(String[] args) throws IOException {
		int[][] c={{},{},{2,4,8,6},{3,9,7,1},{4,6},{},{},
				{7,9,3,1},{8,4,2,6},{9,1}};
		BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
		int n1=Integer.parseInt(r.readLine());
		for(int i1=0;i1<n1;i1++){
			StringTokenizer t=new StringTokenizer(r.readLine());
			int a=Integer.parseInt(t.nextToken())%10;
			int b=Integer.parseInt(t.nextToken());
			int s=0;
			if(b==0){
				s=1;
			}else if(a==0||a==1||a==5||a==6){
				s=a;
			}else{
				int in=(b-1)%c[a].length;
				s=c[a][in];
			}
			System.out.println(s);
		}
	}
}